package org.example.service;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;


@Service
public class HystrixService {
    //正常访问测试
    public String ok_info(){
        return Thread.currentThread().getName() + "OK !!!!!";
    }

    //超时测试
    //HystrixCommand注解 用于指定熔断方法,一旦标注的方法出现问题会调用指定的兜底方法
    //HystrixCommandProperties： HystrixCommand实例的属性
    //timeoutInMilliseconds 设置当前执行的超时时间
    @HystrixCommand(fallbackMethod = "timeoutHandler",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value ="4000" )
    })
    public String timeout_info(){
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return Thread.currentThread().getName() + "timeOut !!!!!";
    }

    public String timeoutHandler(){
        return "访问超时，请稍后重试!!!!!";
    }

    //服务熔断配置，即10s内，发生10次以上的请求，错误率达到60%，则打开断路器，
    // 熔断窗口期过去后，断路器将变成半开（HALF-OPEN）状态，如果这时候发生的请求正常，则关闭，否则又打开
    @HystrixCommand(fallbackMethod = "breakHandler",commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),//启用熔断器
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"), //服务熔断错误阀值，60%
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),//断路器的快照时间窗，也叫做窗口期。断路器的快照时间窗，也叫做窗口期。
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10") //断路器的窗口期内触发断路的请求阈值，默认为20
    })
    public String circuit_break(int id){
        if (id < 0){
            throw new RuntimeException("i不能小于0");
        }
        return "执行成功！！！！！";
    }

    public String breakHandler(int id){
        return "------"+id+"---------进行熔断，请稍后重试!!!!!";
    }






}
